package com.atguigu.gulimall.cart.service.impl;


/**
 * 购物车
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoTo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    private final String CART_PREFIX = "daogumall:cart:";


    /**
     * 获取购物车中某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res=(String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    /**
     * 将商品添加到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //2商品添加新商品到购物车
        //查询是否有这个商品
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();
            //购物车第一次添加这个商品
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1远程查询当前要添加的商品信息
                R info = productFeignService.info(skuId);
                SkuInfoTo skuInfoTo = info.getData("skuInfo", new TypeReference<SkuInfoTo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoTo.getSkuDefaultImg());
                cartItem.setPrice(skuInfoTo.getPrice());
                cartItem.setTitle(skuInfoTo.getSkuTitle());
                cartItem.setSkuId(skuId);
            },executor);

            CompletableFuture<Void> getSkuSaleAtttrVal = CompletableFuture.runAsync(() -> {
                //3远程查询sku组合信息
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAtttrVal).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }else {
            //购物车有这个商品就修改数量
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }
    }




    /**
     * 购物车列表页
     * 1.拦截器封装用户信息
     * 1）已登录状态：封装userId+userKey到ThreadLocal中
     * 2）未登录状态：
     * 2-1）已分配游客标识，封装userKey到ThreadLocal中
     * 2-2）未分配游客标识，命令客户端保存cookie（user-key），并封装userKey到ThreadLocal中
     * 2.根据用户标识获取购物车信息
     * 1）已登录状态
     * 使用userId作为key获取购物车
     * 使用userKey作为key获取游客购物车，如果非空则与用户购物车合并
     * 2）未登录状态
     * 使用userKey作为key获取游客购物车
     * 3.返回cartList列表页
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //1登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            //2如果临时购物车的数据还没有进行合并【合并购物车】
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if(tempCartItems!=null){
                //合并
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }
            //获取当前登录用户的购物车数据(包含合并的临时购物车数据和登录后的购物车数据)
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        }else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }
        return cart;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);

    }
    /**
     * 更改购物车商品选中状态
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }
    /**
     * 改变商品数量
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));

    }
    /**
     * 删除购物项
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取当前用户的购物车所有选中的商品项
     *  1.从redis中获取所有选中的商品项
     *  2.获取mysql最新的商品价格信息，替换redis中的价格信息
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        //远程查询最新价格
                        R data = productFeignService.getPrice(item.getSkuId());
                        String price = data.get("price").toString();
                        item.setPrice(new BigDecimal(price));
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if(values!=null&&values.size()>0){
            List<CartItem> collect=values.stream().map((obj)->{
                String str=(String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1
        String cartKey = "";
        if(userInfoTo.getUserId()!=null){
            //gulimall:cart:1
            cartKey=CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey=CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
